package com.smarthospital.service.impl;

import com.alibaba.fastjson.JSON;
import com.smarthospital.common.Result.CodeMsg;
import com.smarthospital.common.Result.CommonException;
import com.smarthospital.contants.SHConst;
import com.smarthospital.service.WXPayPlatFormCertUpdateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * create by sym  2021/9/13 0:37.
 */
@Service
@Slf4j
public class WXPayPlatFormCertUpdateServiceImpl implements WXPayPlatFormCertUpdateService {



    @Resource
    @Qualifier("wxCertHttpClient")
    private CloseableHttpClient wxCertHttpClient;

    /**
     * 获取商家 微信支付平台证书
     * @return
     */
    @Override
    public String certificates() {
        try {
            return getCert(SHConst.WXPay_urls.certificates);
        } catch (IOException e) {
            return "shi bai";
        }
    }

    /**
     * 获取证书
     * Apache HTTPClient Post
     * @param url
     * @return 状态码 == 200 时返回data
     */
    private String getCert( String url) throws IOException {
        log.info("【httpClient】 get url {} ",url);
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("Accept", "*/*");
        httpGet.addHeader("Content-type","application/json; charset=utf-8");
        CloseableHttpResponse response = (CloseableHttpResponse )wxCertHttpClient.execute(httpGet);
        if (null == response) {
            log.error("【httpClient】 get response为null");
            throw new CommonException(CodeMsg.ERROR_WX_RESP_NULL);
        }
        log.info("【httpClient】 get httpStatus {}",JSON.toJSONString(response.getStatusLine()));
        if (200 != response.getStatusLine().getStatusCode()) {
            throw new CommonException(response.getStatusLine().getStatusCode(),"【微信支付】 "+ response.getStatusLine().getReasonPhrase());
        }
        //会关闭response
        String returnStr = EntityUtils.toString(response.getEntity());
        log.info("【httpClient】 out {}",returnStr);
        return returnStr;
    }
}
